#!/bin/bash
function uninit()
{
    echo -ne "\a"
    rm -rf $w
    echo
}
function downscale()
{
    AAOPTS="$1"
    shift
    INPUT="$1"
    OUTPUT="$2"
    TURBO="$3"
    mplayer -endpos 30 -vc null -af volume=15.1:1 -ao pcm:fast:file=$w/snd.wav -vo null  "$INPUT"  &> /dev/null &
    #&> /dev/null &
    P1=$!
    faac -w -o $w/$OUTPUT.mp4 --obj-type LC -b 64 $w/snd.wav &> /dev/null &
    #&> /dev/null &
    P2=$!
    if [ -z "$TURBO" ] ;  then
	mencoder $AAOPTS -endpos 30 -slang pl  -profile $PROFILE -nosound -o $w/$OUTPUT.avi "$INPUT"
    else
	echo Root password
	sudo renice -12 -p $P2
	sudo nice -n -17 mencoder -slang pl -profile $PROFILE -nosound -o $w/OUTPUT.avi "$I"
    fi
    wait
}

function get_file_info()
{
    mplayer -identify -endpos 0:0  "$1" -vo null -ao null 2> /dev/null | grep -e "^[^= ]*=[^= ]*$" > $w/ident                                                          
    . $w/ident                                                                                                                                                         
}

function compute_scale()
{
    a=$1
    minw=220
    prw=`python -c "print int($minw * $a)"`
    if [[ $prw > 320  ]] ; then 
	
#	let ind=(prw-320)/2
	 echo "dsize=320:240:0,scale=-10:$minw,crop=320:240"
    else
	 echo "dsize=320:240:0,scale==320:240:0,320:-10:crop=320:240"
    fi
}


if [ -n "$1" ]  ; then
    I=$1
    if [ -z $2 ] ; then 
	O=dvd_rip`date`.mp4
    else
	O=$2.mp4
    fi
else
    I=`zenity --entry --title="Nr strumienia DVD (1)"`
    if [ -z "$D" ] ; then
	I=1
    fi
    O=`zenity --entry --title="plik wyjsciowy"`
    if [ "-z" "$O" ] ; then
	exit 1
    fi
    O=$O.mp4
fi
I=dvd://$I
#exit 1
echo "$I:$O:$3"
#exit 1

echo ${PROFILE:=k800noscale}

#trap uninit EXIT

w=$(mktemp -d)
mkfifo $w/snd.wav
get_file_info $I
#mplayer -identify -endpos 0:0  "$I" -vo null -ao null 2> /dev/null | grep -e "^[^= ]*=[^= ]*$" > $w/ident                                                          
#. $w/ident                                                                                                                                                         
sc=`compute_scale $ID_VIDEO_ASPECT`

downscale "-vf $sc" "$I" out1
[ -f "$O" ] && rm "$O"

MP4Box -add $w/out1.mp4 -add $w/out1.avi  "$w/out.mp4"

if [ ${O:0:1} == "#" ] ; then
    ln -sf "$w/out.mp4" "$w/${O:1}"
    if ! obexftp -u 0 -p "$w/${O:1}" ; then
	mv -f "$w/out.mp4" ~/${O:1}
	echo Emergemcy copy
    fi
else
    mv -f "$w/out.mp4" $O
fi


